import React from 'react'
import ReactDOM from 'react-dom'
import './style/global.less';
import { AppContainer } from 'react-hot-loader';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import route from './route';

/**
 * switch 匹配一个
 * switch + exact 精确匹配第一个
 */

const renderRouter = (item) => {
  let params = {
    key: item.path,
    exact: item.exact !== false,
    path: item.path
  };

  if (item.children) {
    params = {
      ...params,
      render: (data) => item.component(data)
    };
  } else {
    params = {
      ...params,
      component: item.component
    };
  }

  return (
    <Route
      {...params}
    >
    </Route>
  );
};
/* eslint-disable */
const App = () => (
  <AppContainer>
    <BrowserRouter>
      <Switch>
        {
          route.map(item => {
            if (item.children) {
              const Layout = item.children.layout;
              item.component = (data) => (
                <Layout key={item.path} {...data}>
                  {
                    item.children.routes.map(children => renderRouter(children))
                  }
                </Layout>
              );
            }
            return renderRouter(item);
          })
        }
      </Switch>
    </BrowserRouter>
  </AppContainer>
);

ReactDOM.render(
  <App/>,
  document.getElementById('app')
);

if (module.hot) {
  module.hot.accept(() => {
    ReactDOM.render(
      <App/>,
      document.getElementById('app')
    );
  });
}
